<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { ElButton } from 'element-plus';
import 'element-plus/dist/index.css';

// 游戏元素引用
const gameCanvas = ref(null);

// 游戏状态
const snake = ref([]);
const food = ref({});
const score = ref(0);
const level = ref(1);
const levelTitle = ref('初学小蛇');
const direction = ref('');
const nextDirection = ref('');
const isPaused = ref(false);
const isGameOver = ref(false);
const isGameStarted = ref(false);
const showStartScreen = ref(true);

// 游戏配置
const gridSize = 20;
const baseGameSpeed = 150; // 基础速度（毫秒）
const gameSpeed = ref(baseGameSpeed);
let gameInterval = null;
let ctx = null;
let tileCount = 30; // 30个格子，600/20=30

// 等级配置
const levelConfig = [
  { score: 0, title: '初学小蛇', speedMultiplier: 1, color: '#3E4C59', labelColor: '#3E4C59', labelTextColor: 'white' },
  { score: 5, title: '贪吃蛇', speedMultiplier: 1.1, color: '#526D82', labelColor: '#526D82', labelTextColor: 'white' },
  { score: 10, title: '灵活蛇', speedMultiplier: 1.2, color: '#9DB2BF', labelColor: '#9DB2BF', labelTextColor: '#27374D' },
  { score: 15, title: '敏捷蛇', speedMultiplier: 1.3, color: '#27374D', labelColor: '#27374D', labelTextColor: 'white' },
  { score: 20, title: '蛇王', speedMultiplier: 1.4, color: '#068DA9', labelColor: '#068DA9', labelTextColor: 'white' },
  { score: 25, title: '黄金蛇王', speedMultiplier: 1.5, color: '#F87171', labelColor: '#F87171', labelTextColor: 'white' },
  { score: 30, title: '超级蛇王', speedMultiplier: 1.6, color: '#FB923C', labelColor: '#FB923C', labelTextColor: 'white' },
  { score: 40, title: '传奇蛇神', speedMultiplier: 1.7, color: '#FBBF24', labelColor: '#FBBF24', labelTextColor: '#27272A' },
  { score: 50, title: '不朽蛇神', speedMultiplier: 1.8, color: '#34D399', labelColor: '#34D399', labelTextColor: '#27272A' },
  { score: 60, title: '宇宙蛇神', speedMultiplier: 1.9, color: '#60A5FA', labelColor: '#60A5FA', labelTextColor: '#27272A' },
  { score: 75, title: '混沌蛇祖', speedMultiplier: 2.0, color: '#A78BFA', labelColor: '#A78BFA', labelTextColor: 'white' },
  { score: 100, title: '创世蛇尊', speedMultiplier: 2.2, color: '#EC4899', labelColor: '#EC4899', labelTextColor: 'white' }
];

// 当前等级配置
const currentLevel = computed(() => {
  return levelConfig[level.value - 1] || levelConfig[0];
});

// 初始化游戏
function initGame() {
  // 重置蛇的位置和长度
  snake.value = [
    { x: 10, y: 10 },
    { x: 9, y: 10 },
    { x: 8, y: 10 }
  ];

  // 设置初始方向
  direction.value = 'right';
  nextDirection.value = 'right';

  // 重置分数
  score.value = 0;

  // 重置等级
  level.value = 1;
  levelTitle.value = '初学小蛇';

  // 重置游戏速度
  gameSpeed.value = baseGameSpeed;

  // 生成食物
  generateFood();

  // 重置游戏状态
  isGameOver.value = false;
  isPaused.value = false;
  isGameStarted.value = true;
  showStartScreen.value = false;

  // 清空画布并重置显示
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, 600, 600);
  drawGrid();
}

// 生成食物
function generateFood() {
  let newFood;
  let onSnake;

  do {
    onSnake = false;
    // 随机生成食物位置
    newFood = {
      x: Math.floor(Math.random() * tileCount),
      y: Math.floor(Math.random() * tileCount)
    };

    // 检查食物是否生成在蛇身上
    for (let i = 0; i < snake.value.length; i++) {
      if (snake.value[i].x === newFood.x && snake.value[i].y === newFood.y) {
        onSnake = true;
        break;
      }
    }
  } while (onSnake);

  food.value = newFood;
}

// 检查并更新等级
function checkLevel() {
  // 从高到低检查当前分数对应的等级
  for (let i = levelConfig.length - 1; i >= 0; i--) {
    if (score.value >= levelConfig[i].score) {
      if (i + 1 !== level.value) {
        level.value = i + 1;
        levelTitle.value = levelConfig[i].title;

        // 更新游戏速度（加快）
        gameSpeed.value = Math.max(50, Math.floor(baseGameSpeed / levelConfig[i].speedMultiplier));

        // 重新设置游戏循环以应用新速度
        clearInterval(gameInterval);
        gameInterval = setInterval(updateGame, gameSpeed.value);
      }
      break;
    }
  }
}

// 绘制游戏
function drawGame() {
  // 清空画布
  ctx.clearRect(0, 0, 600, 600);

  // 绘制网格线
  drawGrid();

  // 绘制蛇 - 使用当前等级对应的颜色
  ctx.fillStyle = currentLevel.value.color;
  for (let i = 0; i < snake.value.length; i++) {
    ctx.fillRect(snake.value[i].x * gridSize, snake.value[i].y * gridSize, gridSize, gridSize);

    // 绘制蛇的眼睛（只有头部有眼睛）
    if (i === 0) {
      ctx.fillStyle = 'white';
      // 根据蛇的方向绘制眼睛位置
      if (direction.value === 'right') {
        ctx.fillRect(snake.value[i].x * gridSize + 5, snake.value[i].y * gridSize + 5, 3, 3);
        ctx.fillRect(snake.value[i].x * gridSize + 12, snake.value[i].y * gridSize + 5, 3, 3);
      } else if (direction.value === 'left') {
        ctx.fillRect(snake.value[i].x * gridSize + 5, snake.value[i].y * gridSize + 5, 3, 3);
        ctx.fillRect(snake.value[i].x * gridSize + 12, snake.value[i].y * gridSize + 5, 3, 3);
      } else if (direction.value === 'up') {
        ctx.fillRect(snake.value[i].x * gridSize + 5, snake.value[i].y * gridSize + 5, 3, 3);
        ctx.fillRect(snake.value[i].x * gridSize + 12, snake.value[i].y * gridSize + 5, 3, 3);
      } else if (direction.value === 'down') {
        ctx.fillRect(snake.value[i].x * gridSize + 5, snake.value[i].y * gridSize + 12, 3, 3);
        ctx.fillRect(snake.value[i].x * gridSize + 12, snake.value[i].y * gridSize + 12, 3, 3);
      }
      ctx.fillStyle = currentLevel.value.color;
    }
  }

  //  绘制食物类型一
  // ctx.fillStyle = '#f44336';
  // ctx.beginPath();
  // ctx.arc(
  //   food.value.x * gridSize + gridSize / 2,
  //   food.value.y * gridSize + gridSize / 2,
  //   gridSize * 0.5,
  //   0, 2 * Math.PI
  // );
  // ctx.fill();

  // 绘制食物 - 结合圆形黄色豆豆和马赛克效果
  const centerX = food.value.x * gridSize + gridSize / 2;
  const centerY = food.value.y * gridSize + gridSize / 2;
  const radius = gridSize * 0.4;
  const pixelSize = Math.floor(gridSize * 0.1); // 马赛克小方块的大小

  // 定义不同深浅的黄色色调
  const yellowShades = ['#ffeb3b', '#ffd700', '#ffc107', '#ffab00'];

  // 在圆形区域内绘制马赛克小方块
  for (let y = -radius; y <= radius; y += pixelSize) {
    for (let x = -radius; x <= radius; x += pixelSize) {
      // 检查当前方块是否在圆形范围内
      if (x * x + y * y <= radius * radius) {
        // 随机选择一种黄色色调
        const randomShade = yellowShades[Math.floor(Math.random() * yellowShades.length)];
        ctx.fillStyle = randomShade;
        // 绘制小方块
        ctx.fillRect(
          centerX + x,
          centerY + y,
          pixelSize,
          pixelSize
        );
      }
    }
  }

  // 添加轻微的高光效果，增强立体感
  ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
  ctx.beginPath();
  ctx.arc(
    centerX - radius * 0.3,
    centerY - radius * 0.3,
    radius * 0.25,
    0, 2 * Math.PI
  );
  ctx.fill();
}

// 绘制网格线函数
function drawGrid() {
  ctx.strokeStyle = '#c0c0c0'; // 适当深度的灰色
  ctx.lineWidth = 1;

  // 绘制垂直线
  for (let x = 0; x <= 600; x += gridSize) {
    ctx.beginPath();
    ctx.moveTo(x, 0);
    ctx.lineTo(x, 600);
    ctx.stroke();
  }

  // 绘制水平线
  for (let y = 0; y <= 600; y += gridSize) {
    ctx.beginPath();
    ctx.moveTo(0, y);
    ctx.lineTo(600, y);
    ctx.stroke();
  }
}

// 更新游戏状态
function updateGame() {
  // 如果游戏暂停，则不执行更新逻辑
  if (isPaused.value) {
    return;
  }

  // 更新方向
  direction.value = nextDirection.value;

  // 获取蛇头位置
  let headX = snake.value[0].x;
  let headY = snake.value[0].y;

  // 根据方向移动蛇头
  if (direction.value === 'right') headX++;
  if (direction.value === 'left') headX--;
  if (direction.value === 'up') headY--;
  if (direction.value === 'down') headY++;

  // 检查碰撞
  // 边界碰撞
  if (headX < 0 || headX >= tileCount || headY < 0 || headY >= tileCount) {
    gameOver();
    return;
  }

  // 自身碰撞
  for (let i = 0; i < snake.value.length; i++) {
    if (snake.value[i].x === headX && snake.value[i].y === headY) {
      gameOver();
      return;
    }
  }

  // 创建新的蛇头
  const newHead = { x: headX, y: headY };

  // 检查是否吃到食物
  if (headX === food.value.x && headY === food.value.y) {
    // 增加分数
    score.value++;

    // 检查等级
    checkLevel();

    // 生成新的食物
    generateFood();

    // 蛇吃到食物后变长一格（不删除尾部）
  } else {
    // 没有吃到食物，删除尾部
    snake.value.pop();
  }

  // 添加新的头部
  snake.value.unshift(newHead);

  // 绘制游戏
  drawGame();
}

// 游戏结束
function gameOver() {
  // 清除游戏循环
  clearInterval(gameInterval);

  // 设置游戏结束状态
  isGameOver.value = true;
}

// 开始游戏
function startGame() {
  // 初始化游戏
  initGame();

  // 启动游戏循环
  gameInterval = setInterval(updateGame, gameSpeed.value);
}

// 退出游戏
function exitGame() {
  // 清除游戏循环
  clearInterval(gameInterval);

  // 重置游戏状态
  isGameOver.value = false;
  isPaused.value = false;
  isGameStarted.value = false;
  showStartScreen.value = true;

  // 清空画布
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, 600, 600);
  drawGrid();
}

// 暂停/继续游戏
function togglePause() {
  isPaused.value = !isPaused.value;

  if (!isPaused.value) {
    // 继续游戏，立即更新一次游戏状态
    updateGame();
  }
}

// 处理键盘输入
function handleKeyDown(e) {
  // 防止方向键滚动页面
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(e.key)) {
    e.preventDefault();
  }

  // 空格键控制暂停/继续
  if (e.key === ' ' && !showStartScreen.value && !isGameOver.value) {
    togglePause();
    return;
  }

  // 根据按键更新方向
  switch (e.key) {
    case 'ArrowUp':
      // 防止蛇直接向上移动（如果当前方向是向下）
      if (direction.value !== 'down') {
        nextDirection.value = 'up';
      }
      break;
    case 'ArrowDown':
      // 防止蛇直接向下移动（如果当前方向是向上）
      if (direction.value !== 'up') {
        nextDirection.value = 'down';
      }
      break;
    case 'ArrowLeft':
      // 防止蛇直接向左移动（如果当前方向是向右）
      if (direction.value !== 'right') {
        nextDirection.value = 'left';
      }
      break;
    case 'ArrowRight':
      // 防止蛇直接向右移动（如果当前方向是向左）
      if (direction.value !== 'left') {
        nextDirection.value = 'right';
      }
      break;
  }
}

// 组件挂载时初始化
onMounted(() => {
  if (gameCanvas.value) {
    ctx = gameCanvas.value.getContext('2d');
    // 初始化画布
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, 600, 600);
    // 初始化时也绘制网格
    drawGrid();
  }

  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown);
});

// 组件卸载时清理
onUnmounted(() => {
  // 清除游戏循环
  clearInterval(gameInterval);

  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown);
});
</script>
<template>
  <div class="game-container">
    <!-- 游戏画布 -->
    <div class="game-page">
      <!-- 正方形的贪吃蛇操作区域 -->
      <div class="page-container">
        <canvas
          ref="gameCanvas"
          width="600"
          height="600"
        ></canvas>
      </div>

      <!-- 美化的分数统计和控制按钮区域 -->
      <div class="game-controls">
        <div class="status-info">
          <div class="score-section">
            <div class="score-icon">★</div>
            <span class="score-text">分数:</span>
            <span class="score-value">{{ score }}</span>
          </div>
          <div class="level-section">
            <div class="level-icon">⚡</div>
            <span class="level-text">等级:</span>
            <span class="level-value">{{ level }}</span>
            <span
              class="level-title"
              :style="{ backgroundColor: currentLevel.labelColor, color: currentLevel.labelTextColor }"
            >
              {{ levelTitle }}
            </span>
          </div>
        </div>
        <div class="button-group">
          <el-button
            v-if="!isGameOver && isGameStarted"
            @click="togglePause"
            type="primary"
            size="large"
          >
            {{ isPaused ? '继续游戏' : '暂停游戏' }}
          </el-button>
        </div>
      </div>
      <!-- 全屏开始游戏界面 -->
      <div
        v-if="showStartScreen"
        class="start-screen"
      >
        <h1>贪吃蛇</h1>
        <p>使用方向键控制蛇的移动<br>按空格键暂停/继续游戏<br>吃到食物增加分数和等级</p>
        <p style="color: #f44336; margin-bottom: 30px;">
          仅适用于电脑端操控</p>

        <el-button
          type="primary"
          size="large"
          @click="startGame"
        >开始游戏</el-button>
      </div>

      <!-- 全屏游戏结束界面 -->
      <div
        v-if="isGameOver"
        class="game-over-screen"
      >
        <h1>游戏结束</h1>
        <div class="final-stats">
          <div class="final-score">
            <div class="final-stats-label">最终分数</div>
            <div class="final-value">{{ score }}</div>
          </div>
          <div class="final-level">
            <div class="final-stats-label">最终等级</div>
            <div class="final-value">{{ level }}</div>
            <div
              class="final-level-title"
              :style="{ backgroundColor: currentLevel.labelColor, color: currentLevel.labelTextColor }"
            >
              {{ levelTitle }}
            </div>
          </div>
        </div>
        <div class="btn-group">
          <el-button
            type="primary"
            size="large"
            @click="startGame"
          >重新开始</el-button>
          <el-button
            type="danger"
            size="large"
            @click="exitGame"
          >退出游戏</el-button>
        </div>
      </div>

      <!-- 全屏暂停游戏界面 -->
      <div
        v-if="isPaused"
        class="pause-screen"
      >
        <h1>游戏暂停</h1>
        <p style="margin-bottom: 20px; font-size: 18px;">按空格键继续游戏</p>
        <div class="btn-group">
          <el-button
            type="primary"
            size="large"
            @click="togglePause"
          >继续游戏</el-button>
          <el-button
            type="danger"
            size="large"
            @click="exitGame"
          >退出游戏</el-button>
        </div>
      </div>
    </div>
  </div>


</template>



<style scoped>
/* 容器样式 */
.game-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--card-bg);
  font-family: 'Arial', sans-serif;
  position: relative;
}

.game-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  width: 516px;
  border: 3px solid #333;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
  position: relative;
}

.game-container .page-container {
  position: relative;
  margin-bottom: 20px;
  width: auto;
  min-height: auto;
  background-color: transparent;
  box-shadow: none;
  border: none;
}

canvas {
  border: 2px solid #333;
  background-color: #fff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
  width: 425px;
  height: 425px;
}

/* 美化分数区域 - 优化布局避免换行 */
.game-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 480px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 8px;
}

/* 分数和等级区域 - 调整布局和空间 */
.status-info {
  display: flex;
  align-items: center;
  gap: 24px;
}

.score-section,
.level-section {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.score-icon,
.level-icon {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  font-size: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.score-icon {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
}

.level-icon {
  background: linear-gradient(135deg, #6c757d, #adb5bd);
}

.score-text,
.level-text {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.score-value,
.level-value {
  font-size: 20px;
  font-weight: bold;
  color: #2196F3;
  min-width: 25px;
  text-align: right;
}

.level-title {
  font-size: 14px;
  font-weight: bold;
  color: white;
  padding: 3px 10px;
  border-radius: 10px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  margin-left: 8px;
  min-width: 80px;
  text-align: center;
  white-space: nowrap;
  border: none;
}

.button-group {
  display: flex;
  gap: 12px;
}

/* 全屏遮罩层样式 */
.start-screen,
.game-over-screen,
.pause-screen {
  position: absolute;
  top: 0;
  left: 0;

  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.85);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  z-index: 10;
  border-radius: 8px;
  backdrop-filter: blur(5px);
}

/* 全屏开始游戏界面样式 */
.start-screen h1 {
  font-size: 56px;
  margin-bottom: 20px;
  background: linear-gradient(45deg, #ffffff, #f0f0f0, #ffffff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  padding: 10px 30px;
  border-radius: 10px;
}

.start-screen p {
  font-size: 20px;
  margin-bottom: 30px;
  color: #e0e0e0;
  text-align: center;
}

/* 结算界面样式 - 美化设计 */
.game-over-screen h1 {
  font-size: 56px;
  margin-bottom: 15px;
  text-shadow: 0 0 15px rgba(255, 0, 0, 0.7);
  background: linear-gradient(45deg, #f44336, #ff7961, #f44336);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  padding: 10px 30px;
  border-radius: 10px;
}

/* 美化结算信息 */
.final-stats {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  margin-bottom: 40px;
  padding: 20px 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.final-score,
.final-level {
  font-size: 28px;
  text-align: center;
}

.final-score {
  color: #ffd700;
  text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
}

.final-level {
  color: #6c757d;
  text-shadow: 0 0 10px rgba(108, 117, 125, 0.5);
}

.final-stats-label {
  font-size: 20px;
  color: #e0e0e0;
  margin-bottom: 5px;
}

.final-value {
  font-size: 32px;
  font-weight: bold;
  color: #ffffff;
}

.final-level-title {
  font-size: 20px;
  font-weight: bold;
  color: white;
  padding: 8px 20px;
  border-radius: 20px;
  margin-top: 5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  border: none;
}

/* 暂停界面样式 */
.pause-screen h1 {
  font-size: 48px;
  margin-bottom: 30px;
  text-shadow: 0 0 15px rgba(255, 152, 0, 0.7);
  background: linear-gradient(45deg, #ff9800, #ffb74d, #ff9800);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 按钮组布局优化 */
.btn-group {
  display: flex;
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-page {
    width: 100%;
    border-radius: 0;
    padding: 10px;
    box-shadow: none;
  }

  canvas {
    width: 100%;
    max-width: 600px;
    height: auto;
    aspect-ratio: 1/1;
  }

  .game-controls {
    width: 100%;
    flex-direction: column;
    gap: 15px;
    padding: 10px;
  }

  .status-info {
    width: 100%;
    justify-content: space-around;
  }

  .button-group {
    width: 100%;
    justify-content: center;
  }
}
</style>
